package com.yiqi.liebang.feature.people.view.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.suozhang.framework.framework.AM;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.rongim.RongGenerate;

import cn.rongcloud.contactcard.Friend;

import java.util.List;

import io.rong.imageloader.core.DisplayImageOptions;
import io.rong.imageloader.core.display.FadeInBitmapDisplayer;

/**
 * Created by AMing on 16/1/14.
 * Company RongCloud
 */
public class FriendListAdapter extends BaseAdapter implements SectionIndexer {
    private static DisplayImageOptions options;
    private Context context;

    private List<Friend> list;

    public FriendListAdapter(Context context, List<Friend> list) {
        this.context = context;
        this.list = list;
    }


    /**
     * 传入新的数据 刷新UI的方法
     */
    public void updateListView(List<Friend> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (list != null) return list.size();
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (list == null)
            return null;

        if (position >= list.size())
            return null;

        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        final Friend mContent = list.get(position);
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.friend_item, parent, false);
            viewHolder.tvTitle =  convertView.findViewById(R.id.tv_visitor_name);
            viewHolder.tvPosition =  convertView.findViewById(R.id.tv_visitor_position);
            viewHolder.tvLetter =  convertView.findViewById(R.id.catalog);
            viewHolder.mImageView = convertView.findViewById(R.id.frienduri);
            viewHolder.tvUserId =  convertView.findViewById(R.id.friend_id);

            viewHolder.mIvBasic =  convertView.findViewById(R.id.iv_user_certification);
            viewHolder.mIvWork =  convertView.findViewById(R.id.iv_user_position);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //根据position获取分类的首字母的Char ascii值
        int section = getSectionForPosition(position);
        //如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
        if (position == getPositionForSection(section)) {
            viewHolder.tvLetter.setVisibility(View.VISIBLE);
            String letterFirst = mContent.getLetters();
            if(!TextUtils.isEmpty(letterFirst)){
                letterFirst = String.valueOf(letterFirst.toUpperCase().charAt(0));
            }
            viewHolder.tvLetter.setText(letterFirst);
        } else {
            viewHolder.tvLetter.setVisibility(View.GONE);
        }
        if (mContent.isExitsDisplayName()) {
            viewHolder.tvTitle.setText(this.list.get(position).getDisplayName());
        } else {
            viewHolder.tvTitle.setText(this.list.get(position).getUserName());
        }
        viewHolder.tvPosition.setText(TextUtils.isEmpty(this.list.get(position).getPosition())?"":this.list.get(position).getPosition()+
                (TextUtils.isEmpty(this.list.get(position).getPosition())?"":this.list.get(position).getPosition())
        );
        String portraitUri = this.list.get(position).getUserHead();
        AM.image().bindToCircleObject(portraitUri,viewHolder.mImageView);
        if (list.get(position).getIsBasic()==1){
            viewHolder.mIvBasic.setVisibility(View.VISIBLE);
        }else {
            viewHolder.mIvBasic.setVisibility(View.GONE);
        }
        if (list.get(position).getIsOccupation()==1){
            viewHolder.mIvWork.setVisibility(View.VISIBLE);
        }else {
            viewHolder.mIvWork.setVisibility(View.GONE);
        }
        if (context.getSharedPreferences("config", Context.MODE_PRIVATE).getBoolean("isDebug", false)) {
            viewHolder.tvUserId.setVisibility(View.VISIBLE);
            viewHolder.tvUserId.setText(list.get(position).getUserUid());
        }
        return convertView;
    }

    @Override
    public Object[] getSections() {
        return new Object[0];
    }

    @Override
    public int getPositionForSection(int sectionIndex) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = list.get(i).getLetters();
            char firstChar = sortStr.charAt(0);
            if (firstChar == sectionIndex) {
                return i;
            }
        }

        return -1;
    }

    @Override
    public int getSectionForPosition(int position) {
        return list==null?0:list.get(position).getLetters().charAt(0);
    }


    final static class ViewHolder {
        /**
         * 首字母
         */
        TextView tvLetter;
        /**
         * 昵称
         */
        TextView tvTitle;
        TextView tvPosition;
        /**
         * 头像
         */
        ImageView mImageView;
        /**
         * userid
         */
        TextView tvUserId;

        ImageView mIvBasic;
        ImageView mIvWork;
    }

    /**
     * app中获取用户头像的接口,此前这部分调用分散在app显示头像的每处代码中,整理写一个方法使app代码更整洁
     * 这个方法不涉及读数据库,头像空时直接生成默认头像
     */
    public String getPortraitUri(Friend userInfo) {
        if (userInfo != null) {
            if (userInfo.getPortraitUri() != null) {
                if (TextUtils.isEmpty(userInfo.getPortraitUri().toString())) {
                    if (userInfo.getUserName() != null) {
                        return RongGenerate.generateDefaultAvatar(userInfo);
                    } else {
                        return null;
                    }
                } else {
                    return userInfo.getPortraitUri().toString();
                }
            } else {
                if (userInfo.getUserName() != null) {
                    return RongGenerate.generateDefaultAvatar(userInfo);
                } else {
                    return null;
                }
            }

        }
        return null;
    }

    public static DisplayImageOptions getOptions() {
        options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.de_default_portrait)
                .showImageOnFail(R.drawable.de_default_portrait)
                .showImageOnLoading(R.drawable.de_default_portrait)
                .displayer(new FadeInBitmapDisplayer(300))
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .build();
        return options;
    }

}
